package cola.project.hellojavaee.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.java.Log;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

@Log
@WebServlet(name = "testServlet" ,value = "/test-servlet")
public class TestServlet extends HttpServlet {

    public TestServlet() {
        System.out.println("我是 TestServlet 的无参构造函数");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("我是 TestServlet 的 init");
        super.init();
    }

    @Override
    public ServletConfig getServletConfig() {
        System.out.println("我是 TestServlet 的 getServletConfig");
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("我是 TestServlet 的 service");

        // 转换为 HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;

        // 获取协议版本
        System.out.println("TestServlet 协议版本为：" +request.getProtocol());
        // 获取 访问者的 IP
        System.out.println("TestServlet 访问者的 IP: "+request.getRemoteAddr());
        // 获取请求方法类型
        System.out.println("TestServlet 请求方法的类型："+request.getMethod());

        // 获取头部信息
        Enumeration<String> enumeration = request.getHeaderNames();

        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            System.out.println(name + ": " + request.getHeader(name));
        }

        // 转换为 HttpServletResponse
        HttpServletResponse response = (HttpServletResponse) res;

        // 设置响应内容类型和编码格式
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        // 写入
        response.getWriter().write("我是 TestServlet 的 service 响应的内容");
    }

    @Override
    public String getServletInfo() {
        System.out.println("我是 TestServlet 的 getServletInfo");
        return null;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("我是 TestServlet 的 doGet 响应的内容");
        System.out.println("我是 TestServlet 的 doGet");
    }



    @Override
    public void destroy() {
        System.out.println("我是 TestServlet 的 destroy");
    }
}
